"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 导入导出、备份恢复工具支持M*兼容性
Case Name   : alter/drop view测试，导出再导入
Create At   : 2023.05.23
Owner       : z@wan005
Description :
    1.创建兼容b库
    2.创建测试表和用户，创建视图后修改视图definer
    3.创建视图后修改视图定义
    4.删除视图
    5.使用gs_dump工具导出库1的数据为自定义归档格式
    6.gs_restore导入
    7.连接导入库使用show create view语句查询视图
    8.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.成功
    7.成功
    8.成功
History     :
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class GsDump0064(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.dbuser_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.db_name = "db_dump_0064"
        self.user_name = "user_dump_0064"
        self.tb_name = "tb_dump_0064"
        self.view_name = "view_dump_0064"
        self.dump_path = os.path.join(macro.DB_BACKUP_PATH, 'dump0064')

    def test_server_tools(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '----step1: 创建兼容b库 expect: 成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"drop database if exists {self.db_name}_01;" \
                  f"create database {self.db_name} dbcompatibility 'b';" \
                  f"create database {self.db_name}_01 dbcompatibility 'b';"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd)
        self.log.info(sql_result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_result,
                      '执行失败:' + text)

        text = '--step2: 创建测试表和用户，创建视图后修改视图definer expect: 成功--'
        self.log.info(text)
        sql_cmd = f"create user {self.user_name} password " \
                  f"'{macro.COMMON_PASSWD}';" \
                  f"create user {self.user_name}_01 password " \
                  f"'{macro.COMMON_PASSWD}';" \
                  f"grant proxy on current_user() to {self.user_name};" \
                  f"grant proxy on current_user() to {self.user_name}_01;" \
                  f"create table {self.tb_name}(c int);" \
                  f"create or replace definer = {self.user_name} view " \
                  f"{self.view_name}(c) as select c from {self.tb_name};" \
                  f"alter definer = {self.user_name}_01 view " \
                  f"{self.view_name}(c) as select c from {self.tb_name};"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name)
        self.log.info(sql_result)
        self.assertEqual(2, sql_result.count(
            self.constant.CREATE_ROLE_SUCCESS_MSG), '执行失败:' + text)
        self.assertEqual(2, sql_result.count('GRANT ROLE'), '执行失败:' + text)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, sql_result,
                      '执行失败:' + text)
        self.assertIn('CREATE VIEW', sql_result, '执行失败:' + text)
        self.assertIn('ALTER VIEW', sql_result, '执行失败:' + text)

        text = '--step3: 创建视图后修改视图定义 expect: 成功--'
        self.log.info(text)
        sql_cmd = f"create table {self.tb_name}_01(col1 int, col2 int);" \
                  f"create table {self.tb_name}_02" \
                  f"(col1 int, col2 int, col3 int);" \
                  f"create or replace definer = {self.user_name} view " \
                  f"{self.view_name}_01(col1, col2) as select col1, col2 " \
                  f"from {self.tb_name}_01;" \
                  f"alter view {self.view_name}_01(col1, col2, col3) as " \
                  f"select * from {self.tb_name}_02;"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name)
        self.log.info(sql_result)
        self.assertEqual(2,
                         sql_result.count(self.constant.TABLE_CREATE_SUCCESS),
                         '执行失败:' + text)
        self.assertIn('CREATE VIEW', sql_result, '执行失败:' + text)
        self.assertIn('ALTER VIEW', sql_result, '执行失败:' + text)

        text = '----step4:删除视图 expect:成功---'
        self.log.info(text)
        sql_cmd = f"create table {self.tb_name}_03(c int);" \
                  f"create or replace definer = {self.user_name} view " \
                  f"{self.view_name}_02(c) as " \
                  f"select c from {self.tb_name}_03;" \
                  f"drop view {self.view_name}_02;"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name)
        self.log.info(sql_result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, sql_result,
                      '执行失败:' + text)
        self.assertIn('CREATE VIEW', sql_result, '执行失败:' + text)
        self.assertIn('DROP VIEW', sql_result, '执行失败:' + text)

        text = '----step5: 使用gs_dump工具导出库1的数据为自定义归档格式 expect: 成功----'
        self.log.info(text)
        gs_dump_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"gs_dump " \
                      f"-p {self.dbuser_node.db_port} " \
                      f"{self.db_name} -F c " \
                      f"-f {self.dump_path}"
        self.log.info(gs_dump_cmd)
        dump_msg = self.dbuser_node.sh(gs_dump_cmd).result()
        self.log.info(dump_msg)
        self.assertIn(f"dump database {self.db_name} successfully",
                      dump_msg, '执行失败:' + text)

        text = '----step6: gs_restore导入 expect: 成功----'
        self.log.info(text)
        gsql_cmd = f"source {macro.DB_ENV_PATH};" \
                   f"gs_restore " \
                   f"-p {self.dbuser_node.db_port} " \
                   f"-d {self.db_name}_01 " \
                   f"{self.dump_path}"
        self.log.info(gsql_cmd)
        gsql_msg = self.dbuser_node.sh(gsql_cmd).result()
        self.log.info(gsql_msg)
        self.assertIn(self.constant.RESTORE_SUCCESS_MSG, gsql_msg,
                      '执行失败:' + text)

        text = '----step7: 连接导入库使用show create view语句查询视图 ' \
               'expect: 视图1的definer修改成功----'
        self.log.info(text)
        sql_cmd = f"show create view {self.view_name};"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=f'{self.db_name}_01')
        self.log.info(sql_result)
        self.assertIn('CREATE OR REPLACE DEFINER = user_dump_0064_01',
                      sql_result, '执行失败' + text)

        self.log.info('查询视图2的定义，修改成功')
        self.log.info(text)
        sql_cmd = f"show create view {self.view_name}_01;"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=f'{self.db_name}_01')
        self.log.info(sql_result)
        self.assertIn('SELECT  * FROM tb_dump_0064_02;', sql_result,
                      '执行失败' + text)

        self.log.info('查询视图3，视图3不存在')
        self.log.info(text)
        sql_cmd = f"show create view {self.view_name}_02;"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=f'{self.db_name}_01')
        self.log.info(sql_result)
        self.assertIn("ERROR:  Table 'public.view_dump_0064_02' doesn't exist",
                      sql_result, '执行失败' + text)

    def tearDown(self):
        text = '---step8: 清理环境 expect: 成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"drop database if exists {self.db_name}_01;" \
                  f"drop user if exists {self.user_name};" \
                  f"drop user if exists {self.user_name}_01;"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname='postgres')
        self.log.info(sql_result)
        rm_cmd = f"rm -rf {self.dump_path}"
        self.log.info(rm_cmd)
        rm_msg = self.dbuser_node.sh(rm_cmd).result()
        self.log.info(rm_msg)
        self.assertEqual(2,
                         sql_result.count(self.constant.DROP_DATABASE_SUCCESS),
                         '执行失败:' + text)
        self.assertEqual(2, sql_result.count('DROP ROLE'), '执行失败:' + text)
        self.assertEqual('', rm_msg)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
